package common.server.aop;

import common.server.entity.InsideRequestMessage;
import common.server.entity.OutsideRequestMessage;
import common.server.exception.ValidException;
import common.server.utils.ValidatorHelper;
import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

/**
 * rest 参数校验aop帮助类
 * 
 * @author Administrator
 * @version [版本号, 2017/11/15 0015]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class RestParamVaildAspectHelper {

	/**
	 *
	 */
	public static RestParamVaildAspectHelper I = new RestParamVaildAspectHelper();

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory
			.getLogger(RestParamVaildAspectHelper.class);

	/**
	 * 参数校验帮助类
	 */
	private RestParamVaildAspectHelper() {
	}

	/**
	 * 请求前
	 * 
	 * @param joinPoint
	 * @throws Throwable
	 */
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		Object[] args = joinPoint.getArgs();
		// Spring 注解校验结果
		BindingResult bindingResult = null;
		// 内部请求参数
		InsideRequestMessage insideRequestMessage = null;
		// 外部请求参数
		OutsideRequestMessage outsideRequestMessage = null;
		if (args != null) {
			for (Object arg : args) {
				if (arg instanceof BindingResult) {
					bindingResult = (BindingResult) arg;
				} else if (arg instanceof InsideRequestMessage) {
					insideRequestMessage = (InsideRequestMessage) arg;
				} else if (arg instanceof OutsideRequestMessage) {
					outsideRequestMessage = (OutsideRequestMessage) arg;
				}
			}
		}
		if (null != bindingResult) {
			//检测spring的校验结果是否有错
			checkBindingResult(bindingResult);
		}
		else {
			if(null != insideRequestMessage){
				//校验内部接口参数
				ValidatorHelper.validator(insideRequestMessage);
			}
			else if(null != outsideRequestMessage){
				//校验外部接口参数
				ValidatorHelper.validator(outsideRequestMessage);
			}
		}

	}

	/**
	 * 检测校验结果
	 *
	 * @param br
	 */
	protected void checkBindingResult(BindingResult br) throws ValidException {
		if (br.hasErrors()) {
			StringBuffer errorAll = new StringBuffer();
			errorAll.append("CHECK-FAIL:[");
			for (ObjectError one : br.getAllErrors()) {
				errorAll.append(one.getDefaultMessage()).append(";");
			}
			errorAll.append("]");
			throw new ValidException(errorAll.toString());
		}
	}
}
